package com.one2manycall.controller;

import java.util.List;

import com.one2manycall.service.RoleService;
import com.one2manycall.vo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


/**
 * 角色管理页面
 */
@Controller
@RequestMapping("/RoleController")
public class RoleController {

    @Autowired
    private RoleService roleService;


    //// 页面部分 开始  /////////////////////////////////////
    @GetMapping("/roles")
    public String listRoles(Model model) {
        List<Role> roles = roleService.getAllRoles();
        model.addAttribute("roles", roles);
        return "html/role/roles";
    }

    @GetMapping("/roles/new")
    public String createRoleForm(Model model) {
        Role role = new Role();
        model.addAttribute("role", role);
        return "html/role/create_role";
    }


    @GetMapping("/roles/edit/{id}")
    public String editRoleForm(@PathVariable Long id, Model model) {
        Role role = roleService.getRoleById(id);
        model.addAttribute("role", role);
        return "html/role/edit_role";
    }

    //// 页面部分 结束  /////////////////////////////////////




    @PostMapping("/roles/save")
    public String saveRole(@ModelAttribute("role") Role role) {
        roleService.saveRole(role);
        return "redirect:/RoleController/roles";
    }



    @PostMapping("/roles/{id}")
    public String updateRole(@PathVariable Long id, @ModelAttribute("role") Role role, Model model) {
        Role existingRole = roleService.getRoleById(id);
        existingRole.setRoleName(role.getRoleName());
        existingRole.setDescription(role.getDescription());
        roleService.saveRole(existingRole);
        return "redirect:/RoleController/roles";
    }

    @GetMapping("/roles/{id}")
    public String deleteRole(@PathVariable Long id) {
        roleService.deleteRoleById(id);
        return "redirect:/RoleController/roles";
    }
}